﻿package com.barry.download;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.barry.download.exception.RequestException;
import com.barry.download.http.impl.MyDownloadFileRequest;
import com.barry.download.manager.DownloadManager;
import com.barry.download.module.DownloadModule;
import com.barry.download.util.Constants;
import com.barry.download.util.MyLog;
import com.barry.download.util.Util;
//代码仅供交流学习，请勿盗作他用，转载请注明出处。创造良好的共同学习环境，大家才会有动力去分享。
public class MainActivity extends Activity
{
    ListView downloadList;
    DownloadAdapter adapter;
    ArrayList<DownloadModule> modules;
    DownloadManager manager;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyLog.setLogLevel(0);
        checkAppDataDir();
        initView();
        initData();
        manager = new DownloadManager(this);
        manager.addDownloadHandler(new MyHandler(this, "downloadTest"));
    }


    private void initView()
    {
        downloadList = (ListView) findViewById(R.id.download_list);
    }


    private void initData()
    {
        modules = new ArrayList<DownloadModule>();
        for (int i = 0; i < 10; i++)
        {
            DownloadModule dm = new DownloadModule();
            dm.setFileName("testFileName" + i + ".mp3");
            dm.setProgress(0);
            dm.setTotal(11030732);
            dm.setTitle("下载项目:" + i);
            modules.add(dm);
        }
        adapter = new DownloadAdapter(this, modules, btnListener);
        downloadList.setAdapter(adapter);
    }
    private void checkAppDataDir()
    {
        File appDataDir = new File(Constants.APP_DATA_PATH);
        if (!appDataDir.exists())
        {
            if (appDataDir.mkdir())
            {
                MyLog.log("MainActivity", "create app data path success", "d");
            }
            else
            {
                MyLog.log("MainActivity", "create app data path fail", "d");
            }
        }
    }
    private OnClickListener btnListener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            DownloadModule dm = (DownloadModule) v.getTag();
            DownloadAdapter.ViewHolder holder = null;

            if (dm == null)
            {
                return;
            }
            holder = getViewHolderByDM(dm);
            switch (v.getId())
            {
                case R.id.btn_download_area:
                case R.id.btn_continue_area:
                    if (holder != null)
                    {
                        holder.btnContinue.setText(Util.getPercentFormat(
                            dm.getProgress(), dm.getTotal()));
                        holder.btnPause.setText(Util.getPercentFormat(
                            dm.getProgress(), dm.getTotal()));
                        if (holder.btnPauseArea.getVisibility() != View.VISIBLE)
                        {
                            showSpecialBtn(holder.btnPauseArea, holder);
                        }
                    }
                    MyDownloadFileRequest dfr = manager.download(dm, false);
                    dm.setDownloadRequest(dfr);
                    break;
                case R.id.btn_pause_area:
                    if (holder != null)
                    {
                        if (holder.btnContinueArea.getVisibility() != View.VISIBLE)
                        {
                            showSpecialBtn(holder.btnContinueArea, holder);
                        }
                    }
                    if (dm.getDownloadRequest() != null)
                    {
                        dm.getDownloadRequest().abortRequest();
                    }
                    break;
                case R.id.btn_open_area:
                    Toast.makeText(getApplicationContext(), "打开……",
                        Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };


    private void showSpecialBtn(LinearLayout showBtnArea,
            DownloadAdapter.ViewHolder holder)
    {
        holder.btnContinueArea.setVisibility(View.GONE);
        holder.btnDownloadArea.setVisibility(View.GONE);
        holder.btnPauseArea.setVisibility(View.GONE);
        holder.btnOpenArea.setVisibility(View.GONE);
        showBtnArea.setVisibility(View.VISIBLE);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if
        // it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * 很关键的一个方法，根据模型对象（或者位置）找到对应的progress相关的VIEW
     * @param dm
     * @return
     */
    private DownloadAdapter.ViewHolder getViewHolderByDM(DownloadModule dm)
    {
        DownloadAdapter.ViewHolder holder = null;
        if (dm != null)
        {
            int index = modules.indexOf(dm);
            if (downloadList.getHeaderViewsCount() > 0)
            {
                index += downloadList.getHeaderViewsCount();
            }
            int firstVisible = downloadList.getFirstVisiblePosition();
            int lastVisible = downloadList.getLastVisiblePosition();
            // 判断是否可见，若可见，才更新进度
            if (index <= lastVisible && index >= firstVisible)
            {
                if (index - firstVisible >= 0)
                {
                    View tmp = downloadList.getChildAt(index - firstVisible);
                    Object tag = tmp.getTag();
                    if (tag instanceof DownloadAdapter.ViewHolder)
                    {
                        holder = (DownloadAdapter.ViewHolder) tag;
                    }
                }
            }
        }
        return holder;
    }

    static class MyHandler extends MyBaseHandler
    {
        private SoftReference<MainActivity> activitySR;


        public MyHandler(MainActivity activity, String id)
        {
            this.activitySR = new SoftReference<MainActivity>(activity);
            this.setId(id);
        }


        @Override
        public void handleMessage(Message msg)
        {
            HashMap<String, Object> callbackObjs = null;
            DownloadModule dm = null;
            if (activitySR.get() == null)
            {
                return;
            }
            switch (msg.what)
            {
                case DownloadManager.DOWNLOAD_ERROR:
                    downloadFailOpt(msg, callbackObjs);
                    break;
                case DownloadManager.DOWNLOAD_PROGRESS_CHANGE:
                    downloadProgressChangedOpt(msg, callbackObjs, dm);
                    break;
                case DownloadManager.DOWNLOAD_SUCCESS:
                    downloadSuccessOpt(msg, callbackObjs, dm);
                    break;
                default:
                    break;
            }
        }


        /**
         * @param msg
         * @param callbackObjs
         * @param dm
         */
        private void downloadSuccessOpt(Message msg,
                HashMap<String, Object> callbackObjs, DownloadModule dm)
        {
            if (msg.obj instanceof HashMap)
            {
                callbackObjs = (HashMap<String, Object>) msg.obj;
            }
            if (callbackObjs != null)
            {
                dm = (DownloadModule) callbackObjs.get("DownloadModule");
            }

            DownloadAdapter.ViewHolder holder = activitySR.get().getViewHolderByDM(
                dm);
            if (holder != null)
            {
                activitySR.get().showSpecialBtn(holder.btnOpenArea, holder);
            }
        }


        /**
         * @param msg
         * @param callbackObjs
         * @param dm
         */
        private void downloadProgressChangedOpt(Message msg,
                HashMap<String, Object> callbackObjs, DownloadModule dm)
        {
            int progress = msg.arg1;
            int total = msg.arg2;
            if (msg.obj instanceof HashMap)
            {
                callbackObjs = (HashMap<String, Object>) msg.obj;
            }
            if (callbackObjs != null)
            {
                dm = (DownloadModule) callbackObjs.get("DownloadModule");
            }
            if (dm != null)
            {
                DownloadAdapter.ViewHolder holder = activitySR.get().getViewHolderByDM(
                    dm);
                if (holder != null)
                {
                    dm.setTotal(total);
                    dm.setProgress(progress);
                    holder.btnPause.setText(Util.getPercentFormat(progress,
                        total));
                    holder.btnContinue.setText(Util.getPercentFormat(progress,
                        total));
                    if (holder.btnPauseArea.getVisibility() != View.VISIBLE)
                    {
                        activitySR.get().showSpecialBtn(holder.btnPauseArea,
                            holder);
                    }
                }
            }
        }


        /**
         * @param msg
         * @param callbackObjs
         */
        private void downloadFailOpt(Message msg,
                HashMap<String, Object> callbackObjs)
        {
            DownloadModule dm;
            String errorMsg = "下载失败";
            if (msg.obj instanceof HashMap)
            {
                callbackObjs = (HashMap<String, Object>) msg.obj;
            }
            if (callbackObjs != null)
            {
                dm = (DownloadModule) callbackObjs.get("DownloadModule");
                RequestException exception = (RequestException) callbackObjs.get("exception");
                // 如果是暂停
                if (exception.getErrorCode() == MyDownloadFileRequest.DOWNLOAD_PAUSE_CODE)
                {
                    errorMsg = exception.getMessage();
                }
                else if (dm != null)
                {
                    errorMsg = "《" + dm.getTitle() + "》，下载失败";
                }
                Toast.makeText(activitySR.get(), errorMsg, Toast.LENGTH_LONG).show();
                if (dm != null)
                {
                    DownloadAdapter.ViewHolder holder = activitySR.get().getViewHolderByDM(
                        dm);
                    if (holder != null)
                    {
                        if (exception.getErrorCode() == MyDownloadFileRequest.DOWNLOAD_PAUSE_CODE)
                        {
                            activitySR.get().showSpecialBtn(
                                holder.btnContinueArea, holder);
                        }
                        else
                        {
                            activitySR.get().showSpecialBtn(
                                holder.btnDownloadArea, holder);
                        }
                    }
                }
            }
        }

    }
}
